/**
 * 登录需要的model，独立的域名空间。
 */
import { stringify } from 'querystring';
import { history } from 'umi';
import { accountLogin, loginCompany, getPageQuery } from '../services/Login';
import { encrypt } from '../utils/utils';
import { HOST } from '../utils/Api';
import { cloneDeep, isEmpty, forEach } from 'lodash';

const Model = {
  namespace: 'enoadLogin', // 命名空间
  state: {
    userData: {},
    companys: [],
  }, // store 数据
  effects: {
    // 副作用 *的是异步方法
    *login({ payload }, { call, put }) {
      payload.password = encrypt(payload.password);
      const response = yield call(accountLogin, payload);
      if (response.code === 200) {
        yield put({
          type: 'setLoginStatus',
          payload: { user: response.data,res:response },
        });
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();

        let { redirect } = params;

        if (redirect) {
          const redirectUrlParams = new URL(redirect);

          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }
        redirect = redirect === 'login' ? '/' : redirect;
        history.replace(redirect || '/');
      }else if (response.code === 210) {
        //有一组公司需要选择。
        yield put({
          type: 'changeLoginStatus',
          payload: { companys: response.data },
        });
      }
    },
    *loginCompany({ payload }, { call, put }) {
      //这里传递两个参数。!companyId || !userId
      const response = yield call(loginCompany, payload);
      if (response.code === 200) {
        yield put({
          type: 'setLoginStatus',
          payload: { user: response.data,res:response },
        });
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();

        let { redirect } = params;

        if (redirect) {
          const redirectUrlParams = new URL(redirect);

          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }
        redirect = redirect === 'login' ? '/' : redirect;
        history.replace(redirect || '/');
      }
    },

    *logout({ payload }, { call, put }) {
      localStorage.removeItem('user');
      let storage = window.sessionStorage;
      storage.removeItem('user'); //控件库使用接口会用到该数据。
      yield put({
        type: 'changeLoginStatus',
        payload: { companys:[] },
      });
      // 不是login界面的话跳转到login界面
      if (window.location.pathname !== '/login') {
        history.replace({
          pathname: '/login',
        });
      }
    },
    *sysConfig({ payload }, { call, put }) {
      window.open(
        `${HOST}:8192/index`,
        '_blank',
      );
    },
  },

  reducers: {
    // effect获取数据处理方法
    setLoginStatus(state, { payload }) {
      localStorage.setItem('user', JSON.stringify(payload.user));
      let storage = window.sessionStorage;
      storage.setItem('user', JSON.stringify(payload.res)); //控件库使用接口会用到该数据。
      return { ...state, ...payload };
    },
    changeLoginStatus(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
export default Model;
